package edu.vt.ece4564;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

public class asyncRequest extends AsyncTask<String, String, Object> {
	// Member fields
	private final static String ip_ = "172.31.137.49";
	private String url_;
	private String classID_;
	private AttendanceActivity a_;
	
	/**
	 * Class Constructor
	 * @author Jason Moskowitz
	 * @param url
	 * @param classID
	 * @param a
	 */
	public asyncRequest(String url, String classID, AttendanceActivity a) {
	    url_ = url;
	    classID_ = classID;
	    a_ = a;
	}
	
	@Override
	protected Object doInBackground(String... params) {
		// TODO Auto-generated method stub
		
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();	//Http GET request stuff
        HttpResponse response;
        //String responseString = null;
        
        String paramString = "";
        HttpGet http;
        
        if(url_.equals("http://" + ip_ + ":8080/getClassInfo?")){
        	List<NameValuePair> params_ = new ArrayList<NameValuePair>();
        	params_.add(new BasicNameValuePair("classID", classID_));
        	paramString = URLEncodedUtils.format(params_, "utf-8");
        	Log.e("URL is:", url_+ paramString);
        	http = new HttpGet(url_+ paramString);
        }
        
        else if(url_.equals("http://" + ip_ + ":8080/registerStudents")){
        	List<NameValuePair> params_ = new ArrayList<NameValuePair>();
        	Map<String, String> m = new HashMap<String, String>();
        	params_.add(new BasicNameValuePair("classID", classID_));
        	params_.add(new BasicNameValuePair("NumberOfStudents", "" + m.size()));
        	for(String s: m.keySet()){
        		params_.add(new BasicNameValuePair(s, m.get(s)));
        		//Log.e("URL is:", url_+ paramString);
        	}
        	paramString = URLEncodedUtils.format(params_, "utf-8");
        	http = new HttpGet(url_+ paramString);
        }
        else if(url_.equals("http://" + ip_ + ":8080/registerAttendance?")){
        	List<NameValuePair> params_ = new ArrayList<NameValuePair>();
        	List<String> l = new ArrayList<String>();
        	params_.add(new BasicNameValuePair("classID", classID_));
        	params_.add(new BasicNameValuePair("NumberOfStudents", "" + l.size()));
        	String header = "";
        	for(String s: l){
        		//params_.add(new BasicNameValuePair(s, "0"));
        		//Log.e("URL is:", url_+ paramString);
        		header = header + s + ";";
        	}
        	paramString = URLEncodedUtils.format(params_, "utf-8");
        	http = new HttpGet(url_+ paramString);
        	http.addHeader("list", header);
        }
        else if(url_.equals("http://" + ip_ + ":8080/getBluetoothMapping?")){
        	List<NameValuePair> params_ = new ArrayList<NameValuePair>();
        	List<String> l = new ArrayList<String>();
        	params_.add(new BasicNameValuePair("classID", classID_));
        	paramString = URLEncodedUtils.format(params_, "utf-8");
        	http = new HttpGet(url_+ paramString);
        }
        else{
        	http = new HttpGet(url_);
        }
        //MultipartEntity mpE = new MultipartEntity();
        try {
        	//http.addHeader("classID", classID_);
			//mpE.addPart("classID", new StringBody(classID_));
			//http.setEntity(mpE);111
			response = client.execute(http);
			
            InputStream iStream = response.getEntity().getContent();
            BufferedReader bReader = new BufferedReader(new InputStreamReader(iStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();
            String line;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }
            iStream.close();
            String temp = sBuilder.toString();
            //temp = temp.substring(1, temp.length()-1);
            JSONObject json = new JSONObject(temp);				//cast the response to a JSON object
            Log.d("asyncTag", temp);
            return temp;
		} catch (UnsupportedEncodingException e1) {
			//e1.printStackTrace();
			Log.e("No worky1", e1.getMessage());
		} catch (ClientProtocolException e) {
			//e.printStackTrace();
			Log.e("No worky2", e.getMessage());
		} catch (IOException e) {
			//e.printStackTrace();
			Log.e("No worky3", e.getMessage());
		} catch (JSONException e) {
			//e.printStackTrace();
			Log.e("URL is: ", url_+ paramString );
			Log.e("No worky4", e.getMessage());
		}
		return null;
	}
	
	protected void onPostExecute(Object result){
		if(url_.equals("http://" + ip_ + ":8080/getClassInfo?")){
			a_.jsonString_ = result.toString();
			Log.d("JSON is", result.toString());
			a_.parseJson(result.toString());
	    }
		else if(url_.equals("http://" + ip_ + ":8080/registerAttendance?")){
	    }
		else if(url_.equals("http://" + ip_ + ":8080/getBluetoothMapping?")){
			//if(result.toString().)
			try {
				a_.jsonString_ = result.toString();
				Log.d("JSON is", result.toString());
				a_.parseToMap(result.toString());
			} catch (NullPointerException e){
				Log.e("NPE", "DAMMIT!");
			}
	    }
		return;
	}
}
